package com.atguigu.crowd.mvc.interceptor;

import com.atguigu.crowd.constant.CrowdConstant;
import com.atguigu.crowd.exception.AccessForbiddenException;
import entity.Admin;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
// 拦截器，用来在未登录时访问受保护页面时进行拦截并抛出AccessForbiddenException
public class LoginIntercepteor extends HandlerInterceptorAdapter {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object object) throws Exception {
        // 1通过requset对象获取session对象
        HttpSession session=request.getSession();
        // 2从session域中取出Admin对象
        Admin admin=(Admin)session.getAttribute(CrowdConstant.LOGIN_ADMIN_NAME);
        // 3判断admin对象是否为空，若为空表示未登录，抛出异常
        if (admin == null){
            throw new AccessForbiddenException(CrowdConstant.MESSAGE_ACCESS_FORBIDDEN);
        }
        // 4admin对象不为空，表示已登录，放行
        return true;
    }
}
